package com.example.mytestapplication;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import org.simple.eventbus.EventBus;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import static android.R.attr.data;
import static android.R.attr.start;

/**
 * Created by wei on 2017/6/23.
 */

public class ScanActivity extends Activity {
    private static String LOG_TAG = "WifiBroadcastActivity";
    private static UdpHelper udpHelper;
    private Context context;
    private volatile boolean start = true;

    private volatile String address = null;
    public static final int DEFAULT_PORT = 43708;
    private static final int CLIENT_PORT = 43608;
    private static final int MAX_DATA_PACKET_LENGTH = 40;
    private byte[] buffer = new byte[MAX_DATA_PACKET_LENGTH];

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_come);
        ImageView imageView = (ImageView) findViewById(R.id.img);
        imageView.setImageResource(R.drawable.starting_come_scan);
        EventBus.getDefault().post("","COME_BACK");

    }

    //写线程
    public class BroadCastUdp extends Thread {
        private String dataString;
        private DatagramSocket udpSocket;

        public BroadCastUdp(String dataString) {
            this.dataString = dataString;
        }

        @Override
        public void run() {
            DatagramPacket dataPacket = null;

            try {

                udpSocket = new DatagramSocket(DEFAULT_PORT);
                dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);
                if(dataPacket == null || udpSocket == null)
                    return ;
                byte[] data = dataString.getBytes();
                dataPacket.setData(data);
                dataPacket.setLength(data.length);
                dataPacket.setPort(DEFAULT_PORT);
                InetAddress addr;
                if (address == null || address.isEmpty()) {
                    addr = InetAddress.getByName("255.255.255.255");
//                    showToast("正在获取盒子ip");
                } else {
                    addr = InetAddress.getByName(address);
                }
                System.out.println("发给：" + addr.getHostAddress().toString());
                dataPacket.setAddress(addr);

            } catch (Exception e) {
//                showToast(e.toString());
                Log.e(LOG_TAG, e.toString());
            }
//            while (start) {
            try {
//                System.out.println("准备：");
                if (udpSocket != null) {
                    udpSocket.send(dataPacket);
                    System.out.println("已发送：" + new String(dataPacket.getData()));
                }
                //sleep(5000);
            } catch (Exception e) {
                showToast(e.toString());
                System.out.println("error：" + e.toString());
            }
//            }
            udpSocket.close();
            System.out.println("关闭。");
        }
    }

    //读线程
    private class UdpReceiver extends Thread {

        @Override
        public void run() {
            DatagramSocket ds = null;
            DatagramPacket dp = null;
            byte[] dataRecv = new byte[1024];
            System.out.println("UdpReceiver started >>>>>");
            try {
                ds = new DatagramSocket(CLIENT_PORT);
                dp = new DatagramPacket(dataRecv, dataRecv.length);
            } catch (SocketException e) {
                e.printStackTrace();
            }
            while (start) {
                try {
                    System.out.println("接收ing");
                    if(ds==null){
                        continue;
                    }
                    ds.receive(dp);
                    System.out.println("接收done");
                    if (dp.getAddress() != null) {
                        final String codeString = new String(dataRecv, 0, dp.getLength());
                        final String boxIp = dp.getAddress().toString().substring(1);

                        if(!TextUtils.isEmpty(boxIp) && TextUtils.isEmpty(address)){
                            address = boxIp;
                            showToast("获取盒子ip成功："+boxIp);
                            new BroadCastUdp("cmd=735000004,N1#").start();
                            new BroadCastUdp("cmd=735000004,N2#").start();
                            new BroadCastUdp("cmd=735000004,N3#").start();
                        }else if(!TextUtils.isEmpty(address) && !address.equals(boxIp)){
                            showToast("盒子ip改变了，重新获取id");
                        }else{
                            new BroadCastUdp("qip").start();
                        }
//                        if (codeString.contains("qip") ||
//                                codeString.contains("rpt")
//                                || codeString.contains("device")) {

//                            Message msg = new Message();
//                            msg.what = 1;
//                            msg.obj = boxIp;
//                            mHandler.sendMessage(msg);
//                        }
                        System.out.println("recv:" + codeString + " from:" + boxIp);
//                        message.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                message.append("\nTV Box:"+boxIp+" return>>>>>>\n");
//                                message.append(codeString + "\n<<<<<<");
//                            }
//                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    showToast(e.toString());
                }
            }
            if (ds != null) {
                ds.close();
            }
            System.out.println("recv:close");
        }
    }
    private Handler handler = new Handler();
    public void showToast(final String message){
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, ""+message, Toast.LENGTH_SHORT).show();
            }
        });
    }

}
